<style lang="scss">
.qus-editor {
  display: flex; gap: 10px; align-items: flex-start;
  &__inner {
    flex: 1;     min-height: 1px;
  }
  .cus-div {
    box-sizing: border-box;
    padding: 5px 0;
    border-bottom: 1px solid #eee;
    word-break: break-all;
  }
  [cus-div-inner] {
    word-break: break-all;
  }
  .ql-snow .ql-picker.ql-size .ql-picker-label::before,
  .ql-snow .ql-picker.ql-size .ql-picker-item::before {
    content: attr(data-value);
  }
  .quill-wrapper[toolbar-bottom] {
    display: flex;
    flex-direction: column;
    > .toolbar {
      order: 21;
    }
    .ql-toolbar.ql-snow + .ql-container.ql-snow {
      border-top: 1px solid #ccc;
      border-bottom: 0;
    }
  }
  .ql-snow{
    .ql-picker{
      &.ql-size{
        .ql-picker-label,
        .ql-picker-item{
          &::before{
            content: attr(data-value) !important;
          }
        }
      }
    }
  }
}
</style>

<template>
  <div class="qus-editor" >
    <div class="qus-editor__inner" >
      <div class="quill-wrapper" :toolbar-bottom="toolBarBottom">
        <div :id="toolbarID" class="toolbar">
          <span class="ql-formats">
             <button class="ql-redo" value="redo">
               <svg viewbox="0 0 18 18">
    <polygon class="ql-fill ql-stroke" points="12 10 14 12 16 10 12 10"></polygon>
    <path class="ql-stroke" d="M9.91,13.91A4.6,4.6,0,0,1,9,14a5,5,0,1,1,5-5"></path>
  </svg>
             </button>
             <button class="ql-undo" value="undo">
               <svg viewbox="0 0 18 18">
<polygon class="ql-fill ql-stroke" points="6 10 4 12 2 10 6 10"></polygon>
<path class="ql-stroke" d="M8.09,13.91A4.6,4.6,0,0,0,9,14,5,5,0,1,0,4,9"></path>
</svg>
             </button>
          </span>
          <span class="ql-formats">
            <select class="ql-font">
              <option selected=""></option>
              <option value="serif"></option>
              <option value="monospace"></option>
            </select>
          </span>
          <span class="ql-formats">
            <button class="ql-bold"></button>
            <button class="ql-italic"></button>
            <button class="ql-underline"></button>
            <button class="ql-strike"></button>
            <select title="Size" class="ql-size">
               <option :value="SizeItem"
               v-for="SizeItem in sizeArr"
               >{{SizeItem}}</option>
            </select>
          </span>
          <span class="ql-formats">
            <select class="ql-color"></select>
            <select class="ql-background"></select>
          </span>
          <span class="ql-formats">
            <button class="ql-list" value="ordered"></button>
            <button class="ql-list" value="bullet"></button>
            <select class="ql-align">
              <option selected=""></option>
              <option value="center"></option>
              <option value="right"></option>
              <option value="justify"></option>
            </select>
          </span>
          <span class="ql-formats">

          </span>
          <span class="ql-formats">
<!--            <button class="ql-attachment"></button>-->
          </span>
<!--          <span class="ql-formats">-->
<!--            <button class="ql-link"></button>-->
<!--            <button class="ql-image"></button>-->
<!--          </span>-->
<!--          <slot name="toolbar" v-bind="exportCtx"></slot>-->
        </div>
        <div :id="editorId" class="editor"></div>
      </div>

    </div>
    <div class="qus-editor__ext">
      <slot name="ext__beforeend" v-bind="exportCtx"></slot>
    </div>
  </div>
</template>

<script>
import Quill from 'quill'
var Block = Quill.import('blots/block');
// console.dir(Block)
class SuperBlock extends Block {
  static create(value) {
    let node = super.create();
    let obj = ZY.JSON5.parse(value);
    // console.log(obj)
    let opt = obj?.opt ?? {}

    node.setAttribute('data-set', '' + ZY.rid(6))
    node.innerHTML = `<span cus-div-inner="" style="color: ${opt.color}">${obj.text}</span>`
    return node;
  }
}
Block.blotName = 'cus-div';
Block.className = 'cus-div'
Block.tagName = 'div';
Quill.register(SuperBlock);

var Embed = Quill.import('blots/embed');
class MyCustomTag extends Embed {
  static create(paramValue) {
    let node = super.create();
    node.innerHTML = paramValue;
    //node.setAttribute('contenteditable', 'false');
    //node.addEventListener('click', MyCustomTag.onClick);
    return node;
  }

  static value(node) {
    return node.innerHTML;
  }
}

MyCustomTag.blotName = 'my-custom-tag';
MyCustomTag.className = 'my-custom-tag';
MyCustomTag.tagName = 'my-custom-tag';
//in case you need to inject an event from outside
/* MyCustomTag.onClick = function(){
     //do something
 }*/

let sizeArr = []
for (let i = 12; i < 60; i = i + 2) {
  sizeArr.push(i + 'px')
}


Quill.register(MyCustomTag);
var Size = Quill.import('attributors/style/size');
Size.whitelist = sizeArr;
Quill.register(Size, true);

import {AttachmentHandler} from "./quill-upload";
Quill.register("modules/attachmentHandler", AttachmentHandler);
// var toolbarOptions = [ 'undo' , 'bold', 'italic', 'underline', 'strike', { 'color': [] }, { 'background': [] }, { 'size': Size.whitelist } ];

export default {
  name: "ZQuillEditor",
  props: {
    toolBarBottom: Boolean,
    value: null,
    modules: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    let self = this
    return {
      quill: null,
      editorId: 'editor' + ZY.rid(),
      toolbarID: 'toolbar' + ZY.rid(),
      sizeArr,
      exportCtx: self
    }
  },
  mounted() {
    let self  = this;
    let quill;
    let editorId = this.editorId;
    let toolbarID = this.toolbarID;

    quill = new Quill('#' + editorId, {
      modules: {
        history: {
          delay: 2000,
          maxStack: 500,
          userOnly: true
        },
        attachmentHandler: {
          upload: file => {
            // return a Promise that resolves in a link to the uploaded image
            return new Promise((resolve, reject) => {
              // ajax().then(data => resolve(data.attachmentUrl));
              resolve('http://localhost:7001/public/img.png')
            });
          }
        },
        toolbar: {
          // container: toolbarOptions,
          container: '#' + toolbarID,
          handlers: {
            redo(e) {
              // console.log(e);
              quill.history.redo();
            },
            undo() {
              quill.history.undo();
            },
            test() {
              console.log('test')
            }
          }
        },
        keyboard: {
          bindings: {
            shift_enter: {
              key: 13,
              shiftKey: true,
              handler: (range, ctx) => {
                // console.log(range, ctx); // if you want to see the output of the binding
                let editor = quill
                editor.insertText(range.index, '\n');
                setTimeout(() => {
                  editor.removeFormat(editor.getLength() - 1);
                }, 30)
              }
            },
            // enter: {
            //   key: 13,
            //   handler: () => { // submit form }
            //   }
            // }
          }
        },
        ...self.modules
      },
      theme: 'snow'
    });
    // quill.keyboard.addBinding({
    //   key: 'enter',
    //   // shortKey: true
    // }, function(range, context) {
    //   console.log(range, context)
    //   // this.quill.formatText(range, 'bold', true);
    // });

    quill.on('text-change', function(delta, oldDelta, source) {
      // if (source === 'api') {
      //   console.log("An API call triggered this change.");
      // } else if (source === 'user') {
      //   console.log("A user action triggered this change.");
      // }
      self.$emit('input', ZY.JSON5.stringify({
        html:  quill.root.innerHTML,
        content: quill.getContents()
      }), quill)
    });

    quill.on('selection-change', range => {
      self.$emit('selection-change', range)
    })

// console.log(quill.root)
    quill.root.addEventListener('blur', function () {
      self.$emit('editor-blur')
    })

    this.quill = quill
  },
  methods: {
    clear() {
      let quill = this.quill
      quill.setContents([])
    },
    insertTest(text, opt) {
      let quill = this.quill
      // if (!quill.hasFocus()) {
      //   quill.focus()
      // }
      // quill.focus()
      let selection = quill.getSelection()
      let index
      let br = ''
      // if (!selection) {
      //   index = quill.getLength() - 1
      // } else {
      //   // br = '\n'
      //   index = selection.index
      // }
      // console.log(selection, br)
      // quill.insertText(index, br + text, {
      //   ...opt
      // })

      let def = ZY.JSON5.stringify({
        opt,
        text
      })
      index = quill.getLength() - 1
      quill.insertEmbed(index, 'cus-div', def);


      setTimeout(() => {
        let _index
        // let selection = quill.getSelection()
        // if (!selection) {
        //   _index = quill.getLength() - 1
        // } else {
        //   _index = selection.index
        // }
        _index = quill.getLength() - 1
        quill.setSelection(_index)
      }, 30)
    },
    getContents() {
      var delta = this.quill.getContents();
      // console.log(delta, this.quill.root.innerHTML)
      return
    },
    insertQuestion() {
      this.insertTest('问：' + ZY.rid() + ZY_EXT.randomStrArr(30).join(''), {
        'color': 'red',
      })
    },
    insertAnwser() {
      this.insertTest('答：'  + ZY.rid() + ZY_EXT.randomStrArr(30).join(''), {
        'color': 'blue',
      })
    }
  }
}
</script>

<style scoped>

</style>
